/**
 * 
 * @param msg string
 * @param callBackFun function | undefined
 */
export function zconfirm(msg : string, callBackFun ?: any) {
	uni.showModal({
		content: msg,
		confirmText: 'Confirm',
		success: function (res) {
			if (res.confirm) {
				callBackFun(true)
			} else if (res.cancel) {
				callBackFun(false)
			}
		},
	})
}
/**
 * 
 * @param msg string
 * @param callBackFun function | undefined
 */
export function zalert(msg : string, callBackFun ?: any) {
	uni.showModal({
		title: 'tip',
		content: msg,
		showCancel: false,
		confirmText: 'Confirm', //  'Confirm'
		success: function () {
			if (callBackFun) {
				callBackFun()
			}
		},
	})
}

/**
 * 
 * @param msg string
 */
export function toast(msg : string) {
	uni.showToast({
		title: msg,
		duration: 2000,
		mask: false,
		icon: 'none',
	})
}

/**
 * 
 * @param origin Object
 * @param target Object
 */
export const deepClone = function (origin, target : object = {}) {
	for (const prop in target) {
		if (target[prop] !== null && typeof target[prop] === 'object') {
			origin[prop] = Object.prototype.toString.call(target[prop]) === '[object Array]' ? [] : {}
			deepClone(origin[prop], target[prop])
		} else {
			origin[prop] = target[prop]
		}
	}
}


// Date， Date String
// (M)、(d)、(h)、(m)、(s)、(q)  1-2 ，
// (y) 1-4 ，(S) 1 ( 1-3 )
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
// eslint-disable-next-line no-extend-native
Date.prototype.Format = function (fmt) {
	var o = {
		'M+': this.getMonth() + 1, // 
		'd+': this.getDate(), // 
		'h+': this.getHours(), // 
		'm+': this.getMinutes(), // 
		's+': this.getSeconds(), // 
		'q+': Math.floor((this.getMonth() + 3) / 3), // 
		'S': this.getMilliseconds() // 
	}
	if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length)) }
	for (var k in o) {
		if (new RegExp('(' + k + ')').test(fmt)) { fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length))) }
	}
	return fmt
}
	/**
	 *  - 
	 * @param num 
	 * @returns ()
	 */
export const convertNumbers = (num: any,rate:any) => {
	const rateAllocation = uni.getStorageSync('rateAllocation');
	if(rate==1){
		 return num;
	}
  const n = Number(num);
  if (isNaN(n)) return '0';

  const converted = (n / rateAllocation) * rate;

  // ，
  const fixedStr = converted.toFixed(2);

  //  0 
  return fixedStr.replace(/\.?0+$/, '');
}
export function formatTimeToStr(times, pattern) {
	var d = new Date(times).Format('yyyy-MM-dd hh:mm:ss')
	if (pattern) {
		d = new Date(times).Format(pattern)
	}
	return d.toLocaleString()
}

//
// export const formatDate = (time) => {
//   if (time !== null && time !== "") {
//     var date = new Date(time);
//     return formatTimeToStr(date, "yyyy-MM-dd hh:mm:ss");
//   } else {
//     return "";
//   }
// };

export const formatDate = (timestamp : any) => {
	const date = new Date(timestamp);

	const year = date.getUTCFullYear();
	const month = String(date.getUTCMonth() + 1).padStart(2, '0');
	const day = String(date.getUTCDate()).padStart(2, '0');
	const hours = String(date.getUTCHours()).padStart(2, '0');
	const minutes = String(date.getUTCMinutes()).padStart(2, '0');
	const seconds = String(date.getUTCSeconds()).padStart(2, '0');

	return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

export const getUuid = () => {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";
    var uuid = s.join("");
    return uuid;
}

export const checkFirstVisit = () => {
  try {
    const hasVisited = uni.getStorageSync('hasVisited');
    if (!hasVisited) {
      // ，
      uni.setStorageSync('hasVisited', 'true');
      return true;
    }
    return false;
  } catch (e) {
    console.error(':', e);
    return false;
  }
}

/**
 * 
 * @param {number} num1 
 * @param {number} num2 
 * @returns {number} 
 */
export const add = (num1, num2)  => {
  // 
  const num1Str = num1.toString();
  const num2Str = num2.toString();

  // 
  const num1Decimals = num1Str.includes('.') ? num1Str.split('.')[1].length : 0;
  const num2Decimals = num2Str.includes('.') ? num2Str.split('.')[1].length : 0;

  // 
  const maxDecimals = Math.max(num1Decimals, num2Decimals);
  // ，
  const multiplier = Math.pow(10, maxDecimals);
  const result = (num1 * multiplier + num2 * multiplier) / multiplier;
  return Number(result.toFixed(maxDecimals));
}
export function isDevelopment(origin, target) {
  if (process.env.NODE_ENV === 'development') return '/src'
  return ''
}
export const isRunningInPWA = () => {
  // 方法1：通过 display-mode 检测
  const isStandalone = window.matchMedia('(display-mode: standalone)').matches
  const isFullscreen = window.matchMedia('(display-mode: fullscreen)').matches
  const isMinimalUI = window.matchMedia('(display-mode: minimal-ui)').matches

  // 方法2：通过启动方式 (iOS 可能需要额外处理)
  const isLaunchedFromHomeScreen = 'standalone' in window.navigator && window.navigator.standalone

  return isStandalone || isFullscreen || isMinimalUI || isLaunchedFromHomeScreen
}

/**
 * 
 * @param {...number} numbers 
 * @returns {number} 
 */
export const addMultiple = (...numbers) => {
  return numbers.reduce((sum, current) => add(sum, current), 0);
}
